import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { defaultData, Vmp, VmpEntity } from './interface'
import { store as MccStore } from '../../store'
import { fetchGetVmpParams, fetchGetVmpSinglePoll, fetchStartVmp, fetchStopVmp } from '@/api/manager/vmp'
import { subscribeWithSelector } from 'zustand/middleware'
import { VmpStateType, VmpStore } from './store.type'
import { transVmpDTO } from './translator'
import { Message } from '@kedacom/react-next'
import Alert from '@/components/Alert'

const initialState: VmpStateType = {
	isOpen: false,
	data: defaultData,
	batchMembers: [],
	_isStart: false,
	_isEdit: false,
	_preData: null,
	isShowPlanOperateModal: false,
	_pollMembers: [],
	pollModalIsOpen: false,
	localStoragePreName: '',
	vmpParamsName: '',
	vmpState: 0,
	poll_select_mt_key: '',
	PollPlanDetail: null,
	memberList: [],
	callingMap: {},
	_message_flag: '',
}
export const store = createVanilla<VmpStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		updateData: (data) => {
			let _data: Vmp = data ? data : defaultData
			let meetingType = MccStore.getState().mccInfo.meetingType
			if (meetingType === 2) {
				_data.mode = 1
			}
			set({ data: _data })
		},
		msgHandle: async (data: VmpEntity) => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			const { _isStart, _isEdit, update, updateData, _setSessionStage } = get()
			let vmpData: VmpEntity = JSON.parse(JSON.stringify(data))
			update({ _isStart: vmpData.state === 0 ? false : true })
			if (vmpData.state === 0) {
				//停止画面合成保留设置数据
				update({ _isEdit: false })
				return
			}
			let isNeedGetPoll = false
			if (vmpData) {
				vmpData.members?.forEach((item) => {
					if (item.member_type === 6) {
						isNeedGetPoll = true
					}
				})
				if (isNeedGetPoll) {
					const res = await fetchGetVmpSinglePoll(meetingMoid)
					if (res.success && res.list) {
						res.list.forEach((i) => {
							let item = vmpData.members?.find((j) => j.chn_idx === i.chn_idx)
							if (item?.poll && i.poll?.members) {
								item.poll.members = i.poll?.members
							}
						})
					}
				}
			}
			update({ _preData: vmpData }) //记录数据
			if (_isStart && _isEdit) return
			let _data = new Vmp(vmpData)
			updateData(_data) //更新store全部数据
			_setSessionStage(vmpData) //更新缓存 缓存new Vmp 数据
		},
		reset: () => set(initialState),
		onClose: () => {},
		onInit: () => {},
		setCalling: (mtKey) => {
			let callingMap = get().callingMap
			if (callingMap[mtKey]) {
			} else {
				let timeout = setTimeout(() => {
					clearTimeout(callingMap[mtKey]?.timeout)
					let callingMapNow = get().callingMap
					delete callingMapNow[mtKey]
					set({ callingMap: { ...callingMapNow } })
				}, 2000)
				callingMap[mtKey] = {
					timeout,
					isCall: true,
				}
				set({ callingMap: { ...callingMap } })
			}
		},
		_translateVmpParamsToStartVmp: (para) => {
			return new Vmp(para)
		},
		_fetchVmpParams: async (successCallBack, errorCallBack) => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			fetchGetVmpParams(meetingMoid).then((res) => {
				if (res.success) {
					successCallBack(res.data)
				} else {
					errorCallBack()
				}
			})
		},
		_start: async (_para) => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			const { update } = get()
			if (!_para) return
			let data = transVmpDTO(_para) /**9.0可以直接进行画面合成数据*/
			fetchStartVmp(meetingMoid, JSON.stringify(data)).then((res) => {
				if (res.success) {
					update({ _message_flag: 'vmp_start' })
				} else {
					Alert(res.description || '开始画面合成失败')
				}
			})
		},
		_stop: async () => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			const { update } = get()
			fetchStopVmp(meetingMoid).then((res) => {
				if (res && res.success) {
					update({ _message_flag: 'vmp_stop' })
				} else {
					Alert(res.description || '停止画面合成失败')
				}
			})
		},
		_setSessionStage: (para) => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			window.sessionStorage.setItem('vmp$' + meetingMoid, JSON.stringify(para))
		},
		_getStageName: () => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			let _key = 'vmp$' + meetingMoid
			let _stage = window.sessionStorage.getItem(_key)
			if (_stage) {
				return JSON.parse(_stage)?.name ?? ''
			}
			return ''
		},
		_messageInfo: (state) => {
			const type = get()._message_flag
			let info = ''
			if (type === 'vmp_start' && state === 1) {
				info = t('会议画面合成已开始')
			}
			if (type === 'vmp_apply') {
				info = t('会议画面合成已更新')
			}
			if (type === 'vmp_stop' && state === 0) {
				info = t('会议画面合成已停止')
			}
			info && Message.info(info)
			set({ _message_flag: '' })
		},
		_getSessionStage: () => {
			let meetingMoid = MccStore.getState().mccInfo.meetingMoid
			let _key = 'vmp$' + meetingMoid
			let _stage = window.sessionStorage.getItem(_key)
			if (_stage) {
				return JSON.parse(_stage)
			}
			return null
		},
		_getDefaultData: (): VmpEntity => {
			return {
				mt_name_style: {
					font_color: '#FFFFFF',
					font_size: 1,
					position: 1,
				},
				broadcast: 1,
				except_self: 0,
				layout: 0,
				members: [],
				mode: 2,
				show_mt_name: 1,
				id: '',
				name: '',
				voice_hint: 1,
			}
		},
	}))
)
export const useVmpStore = create(store)
